<template>
  <div>
    <el-header style="height: 40px">
      <div style="margin-top: 40px;">
        <el-divider><strong style="font-size: 25px;">在线学习中心</strong></el-divider>
      </div>

    </el-header>
    <div>
      <!--      height: 631px;-->
      <el-container style="height:730px;border: 1px solid #ededed;overflow:scroll">
        <el-aside style="height:100%;">
          <el-tree node-key="id" :data="data" :props="defaultProps" :default-expanded-keys="expandedKeys"
            @node-click="handleNodeClick" :highlight-current="true">
            <template slot-scope="{ node }">
              <span class="span-ellipsis" :title="node.label">{{ node.label }}</span>
            </template>
          </el-tree>
        </el-aside>

        <el-dialog :visible="dialogVisible" title="视频播放到一半啦！请准备核实人脸" :before-close="handleClose">
          <div>
            <video ref="cameraVideo" autoplay playsinline style="width: 100%; height: auto;"></video>
            <el-button type="primary" plain style="margin-left: 45%;" @click="searchPhoto">拍照（识别）</el-button>
            <!--
            <el-button type="primary" plain style="margin-left: 10px" @click="takePhoto">拍照（注册）</el-button>
            -->
            <canvas ref="cameraCanvas" style="display: none;"></canvas>
            <img :src="photoUrl" alt="拍照图片" v-if="photoUrl" style="width: 100%; height: auto;">
          </div>
          <!--          <span slot="footer" class="dialog-footer">
          &lt;!&ndash;
                  <el-button @click="dialogVisible = false">关闭</el-button>
          &ndash;&gt;
              </span>-->
        </el-dialog>

        <el-container>
          <!--          视频播放-->
          <div v-if="VideoVisible">
            <video ref="myVideo" height="98%" controls>
              <source :src="url" type="video/mp4">
              您的浏览器不支持视频标签。
            </video>
          </div>
          <!--          pdf播放-->
          <div v-if="type">
            <iframe :src="url" style="width: 800px;height: 98%;margin-left: 20%;"></iframe>
          </div>
          <!--          考试-->
          <div v-if="testVisible">
            <div>
              <el-card v-for="question in testQuestionList" :key="question.id"
                style="width: 600px;margin-bottom: 5px;margin-left: 40%;" :ref="`card-${question.id}`" shadow="hover">
                <div slot="header" class="clearfix">
                  <span>Question {{ question.code }}：{{ question.question }}</span>
                </div>
                <div v-if="question.type === '单选' || question.type === '多选'" class="radio-group">
                  <el-radio-group v-model="ans[question.id]" v-if="question.type === '单选'"
                    @change="handleChange(question)">
                    <el-radio :label="'A'">A：{{ question.a }}</el-radio>
                    <el-radio :label="'B'">B：{{ question.b }}</el-radio>
                    <el-radio :label="'C'">C：{{ question.c }}</el-radio>
                    <el-radio :label="'D'">D：{{ question.d }}</el-radio>
                  </el-radio-group>

                  <el-checkbox-group v-model="ans[question.id]" v-if="question.type === '多选'" class="checkbox-group"
                    @change="handleChange(question)">
                    <el-checkbox :label="'A'">A：{{ question.a }}</el-checkbox>
                    <el-checkbox :label="'B'">B：{{ question.b }}</el-checkbox>
                    <el-checkbox :label="'C'">C：{{ question.c }}</el-checkbox>
                    <el-checkbox :label="'D'">D：{{ question.d }}</el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-if="question.type === '判断'">
                  <el-radio-group v-model="ans[question.id]" @change="handleChange(question)">
                    <el-radio :label="'对'">正确</el-radio>
                    <el-radio :label="'错'">错误</el-radio>
                  </el-radio-group>
                </div>

              </el-card>
              <div>
                <el-button style="margin-top: 50px;float: right;" type="danger" @click="validateAnswers"
                  v-if="testVisible">提交试卷
                </el-button>
              </div>
            </div>
          </div>

          <div style="width: 220px;position: absolute;top: 10vh;right: 10vh" v-if="testVisible">
            <div style="margin: 15px;margin-left: 75px;">试题列表</div>
            <span v-for="(question, index) in testQuestionList" :key="question.id">
              <el-button @click="scrollToCard(question.id)" :type="click[question.id] ? 'primary' : 'default'"
                style="margin-right: 5px;margin-bottom: 5px;float: left;">
                <span> {{ question.code }}</span>
              </el-button>
              <br v-show="index % 4 === 0 && index > 0">
            </span>

          </div>

          <h1 v-show="myScoreVisible" style="margin-left: 400px;margin-top: 300px">{{ myScore }}</h1>
        </el-container>


      </el-container>
      <el-footer>交通运输人员就业与再就业教育培训平台 ©2024 Created by 重庆交通大学22级计算机科学与技术曙光班 向鸿锐&肖鸿源&谭昌平
      </el-footer>

    </div>
  </div>
</template>
<script>


import { getDocumentVideo } from "@/api/documentVideo";
import { addVideoLearningRecords, getVideoLearningRecords } from "@/api/videoLearningRecords";
import da from "element-ui/src/locale/lang/da";
import { getTestQuestionListForTest, selectedQuestionAndScore } from "@/api/testPaper";
import { addScore } from "@/api/Score";
import { addLearningSituation } from "@/api/learningSituation";
import { addFace, searchFace } from "@/api/faceRegistration";
import { getInfo } from "@/api/user";
import { removeToken } from "@/utils/auth";
import Router from "@/router";

export default {
  data() {
    return {
      dialogVisible: false,
      data: [
        {
          id: 1,
          label: '视频学习',
          children: []
        },
        {
          id: 2,
          label: '文档学习',
          children: []
        },
        {
          id: 3,
          label: '考试中心',
          children: []
        }
      ],
      xmUser: localStorage.getItem("xm-user") ? JSON.parse(localStorage.getItem("xm-user")) : {},

      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'label'
      },
      expandedKeys: [], // 初始时不展开任何节点
      userInFor: {},
      trainingPlanId: 1,
      url: '',
      user_id: 1,
      myInfo: {},
      VideoVisible: false,
      documentVideo: {},
      type: false,
      testVisible: false,
      testQuestionList: [],
      //考试：
      selectedOfOne: '',
      selectedOfMore: [],
      ans: {},//存储所有答案
      selectedAnswers: {},
      click: [],//判断试题是否做
      myScore: '',
      myScoreVisible: false,
    };
  },

  methods: {
    handleClose(done) {
      // 阻止弹窗关闭
      done(false);
    },
    getDocumentVideos() {
      var searchParams = new URLSearchParams(window.location.search);
      var trainPlanId = searchParams.get('trainPlanId');
      this.trainingPlanId = parseInt(trainPlanId, 10);
      getDocumentVideo(this.trainingPlanId, false).then((res) => {
        console.log(res)
        if (res.data.code === 1) {
          this.documentVideos = res.data.data;
          this.documentVideos.forEach(resource => {
            // 判断资源类型
            if (resource.url.endsWith('.mp4') || resource.url.endsWith('.mov') || resource.url.endsWith('.avi')) {
              // 视频类型
              this.data[0].children.push({
                id: resource.id,
                label: resource.name,
                url: resource.url
              });
            } else {
              // 其他类型，可以放入考试或其他分类
              this.data[1].children.push({
                id: resource.id,
                label: resource.name,
                url: resource.url
              });
            }
          });
          //跳转版本返回优化
          //this.expandTreeNode(11);
          // 获取当前URL的查询参数
          //var searchParams = new URLSearchParams(window.location.search);
          //var treeNodeId = parseInt(searchParams.get('treeNodeId'), 10);//必须数字，666
          //console.log('treeNodeId',treeNodeId)
          //this.expandTreeNode(treeNodeId);
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {
      })
    },
    handleNodeClick(data) {
      if (data.id === 3) {
        //试卷
        this.type = false;
        this.VideoVisible = false;
        this.getTestQuestionsListForTest();
        return;
      }

      // 添加自定义文字到查询参数
      console.log(data);
      if (data.url == null) {
        return
      }
      this.documentVideo.id = data.id;
      this.documentVideo.name = data.name;
      this.documentVideo.url = data.url;

      this.VideoVisible = false;
      this.testVisible = false;
      this.myScoreVisible = false;
      this.type = false;

      if (data.url.endsWith('.mp4') || data.url.endsWith('.mov') || data.url.endsWith('.avi')) {
        this.url = data.url;
        //确保数据存在
        this.$nextTick(() => {
          this.VideoVisible = true;
          this.$nextTick(() => {
            this.initVideoPlayer();
          });
        });
      }
      //跳转版本
      /*else if (data.url.endsWith('.pdf')) {
        // 获取当前URL的查询参数
        var searchParams = new URLSearchParams(window.location.search);
        var trainPlanId = searchParams.get('trainPlanId'); // 获取treeNodeId参数
        //浏览pdf
        window.location.href = 'http://localhost:8081/pdfjs-4.9.155-dist/web/viewer.html?file='
            + data.url +"&trainPlanId="+trainPlanId+ "&treeNodeId="+data.id;
      }*/
      //不跳转版本
      else if (data.url.endsWith('.pdf')) {
        //浏览pdf
        this.url = 'http://localhost:8081/pdfjs-4.9.155-dist/web/viewer.html?file=' + data.url;
        this.type = true;
        addLearningSituation(this.trainingPlanId, this.documentVideo.id, 100).then((res) => {
        }).catch((e) => {
        })

      } else {
        addLearningSituation(this.trainingPlanId, this.documentVideo.id, 100).then((res) => {
        }).catch((e) => {
        })
        window.open(data.url, '_blank');
      }

    },
    /*expandTreeNode(treeNodeId) {
      // 设置特定的树节点展开
      this.expandedKeys = [treeNodeId];
    },*/
    initVideoPlayer() {
      const video = this.$refs.myVideo;
      if (video) {
        video.addEventListener('loadedmetadata', () => {
          var searchParams = new URLSearchParams(window.location.search);
          var trainPlanId = searchParams.get('trainPlanId');
          // 设置开始时间
          getVideoLearningRecords(trainPlanId, this.documentVideo.id).then((res) => {
            if (res.data.code === 1) {
              video.currentTime = parseFloat(res.data.data);
            } else {
              console.log("暂无记录或查询失败");
            }
          }).catch((e) => {
            console.error(e);
          });

          // 计算视频一半的时间点
          const halfTime = video.duration / 2;

          // 定义时间更新事件的处理函数
          const handleTimeUpdate = () => {
            // 判断当前播放时间是否接近一半的时间点，这里设置一个容差值，比如5秒
            if (Math.abs(video.currentTime - halfTime) <= 1) {
              // 暂停视频
              video.pause();
              // 显示弹窗
              this.initCamera();
              this.dialogVisible = true;
              // 取消事件监听，避免重复弹出弹窗
              video.removeEventListener('timeupdate', handleTimeUpdate);
            }
          };

          // 监听视频播放时间更新
          video.addEventListener('timeupdate', handleTimeUpdate);
        });

        video.addEventListener('pause', () => {
          console.log(`视频已暂停，当前播放到的时间是：${video.currentTime}秒`);
          // 切换或者播放完毕以及暂停，均会触发
          var searchParams = new URLSearchParams(window.location.search);
          var trainPlanId = searchParams.get('trainPlanId');
          let time = Math.floor(video.currentTime);
          addVideoLearningRecords(trainPlanId, this.documentVideo.id, time).then((res) => {
            if (res.data.code === 1) {
              // console.log("记录成功");
            } else {
              console.log(res.data.msg);
            }
          }).catch((e) => {
            console.error(e);
          });

          let playbackPercentage = Math.floor((video.currentTime / video.duration) * 100);
          // console.log("playbackPercentage", playbackPercentage);
          addLearningSituation(this.trainingPlanId, this.documentVideo.id, playbackPercentage).then((res) => {
          }).catch((e) => {
            console.error(e);
          });
        });
      }
    },
    initCamera() {
      navigator.mediaDevices.getUserMedia({ video: true })
        .then(stream => {
          this.cameraStream = stream;
          this.$refs.cameraVideo.srcObject = stream;
        })
        .catch(error => {
          console.error('获取摄像头权限失败', error);
          this.$message.error('获取摄像头权限失败，请确保摄像头可用并重新尝试。');
        });
    },
    quit() {
      removeToken();
      // this.$message.success("退出成功");
      Router.push('/login');
    },
    closeCamera() {
      if (this.cameraStream) {
        // 关闭摄像头流中的所有轨道
        this.cameraStream.getTracks().forEach(track => {
          track.stop();
        });
        this.cameraStream = null; // 清空摄像头流引用
        this.$refs.cameraVideo.srcObject = null; // 清空视频元素的源对象
      }
    },
    takePhoto() {
      if (this.cameraStream) {
        const canvas = this.$refs.cameraCanvas;
        const video = this.$refs.cameraVideo;
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
        const photoData = canvas.toDataURL('image/jpeg');

        // 调试：检查Base64字符串是否正确
        console.log(photoData);

        // 将照片数据发送到服务器
        addFace({ photoData: photoData.split(',')[1], userId: this.myInfo.id }).then(res => {
          if (res.data.code === 1) {
            this.$message.success('成功加入人脸库');
            // 如果有其他成功后的操作，可以在这里添加
          } else {
            this.$message.error('加入人脸库失败：' + res.data.msg);
          }
        }).catch(e => {
          this.$message.error('加入人脸库失败：' + e.message);
        });

        this.photoUrl = photoData;
      }
    },
    searchPhoto() {
      if (this.cameraStream) {
        const canvas = this.$refs.cameraCanvas;
        const video = this.$refs.cameraVideo;
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
        const photoData = canvas.toDataURL('image/jpeg');

        // 调试：检查Base64字符串是否正确
        console.log(photoData);
        this.userInFor.photoData = photoData.split(',')[1];
        this.userInFor.photoData = this.xmUser.id;
        // 将照片数据发送到服务器
        /*
                searchFace({ photoData: photoData.split(',')[1],userId: this.xmUser.id }).then(res => {
        */
        console.log(photoData.split(',')[1])
        console.log(this.xmUser.id)
        searchFace({ photoData: photoData.split(',')[1], userId: this.myInfo.id }).then(res => {

          console.log(res.data.data)
          if (res.data.code === 1) {
            /*const { user_id, score } = res.data.data;*/
            // 显示成功消息，包括用户ID和相似度
            this.$message.success(`人脸识别成功`);
            // 如果有其他成功后的操作，可以在这里添加

            // video.play();

          } else {
            //this.initVideoPlayer()
            this.quit()
            this.$message.error('人脸识别失败：' + res.data.msg);
          }
        }).catch(e => {
          this.quit()
          this.$message.error('人脸识别失败：' + e.message);
        });
        if (this.user_id == 1) {
          this.dialogVisible = false;
          this.closeCamera();
        } else {

        }

        this.photoUrl = photoData;
      }
    },

    getMyInfo() {
      getInfo().then((res) => {
        if (res.data.code === 1) {
          this.myInfo = res.data.data;
          console.log(this.myInfo)
        }
      }).catch((e) => {
      })
    },

    //考试试题列表
    getTestQuestionsListForTest() {
      selectedQuestionAndScore(this.trainingPlanId).then((res) => {
        console.log(res)
        if (res.data.code === 1) {
          let code = 1; // 初始化code从1开始
          this.testQuestionList = res.data.data.map(question => {
            // 添加code属性到每个question对象
            return {
              ...question, // 展开原有的question属性
              code: code++ // 添加新的code属性，并且每次调用时递增
            };
          });
          this.ans = this.testQuestionList.reduce((acc, question) => {
            // 对于单选题和判断题，默认答案可以是一个空字符串
            // 对于多选题，默认答案应该是一个空数组
            acc[question.id] = question.type === '多选' ? [] : '';
            return acc;
          }, {});

          if (this.testQuestionList.length !== 0) {
            this.testVisible = true;
          }

        } else {
          this.testVisible = false;
          this.myScore = res.data.msg;
          this.myScoreVisible = true;
        }
      }).catch((e) => {
      })
    },
    handleChange(question) {
      this.$set(this.click, question.id, true);
      console.log(question)
    },

    validateAnswers() {
      this.$confirm("是否交卷", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let score = 0;
        let allSocre = 0;
        this.testQuestionList.forEach(question => {
          if (question.type === '单选' || question.type === '判断') {
            if (this.ans[question.id] === question.ans) {
              score += question.score;
            }
            allSocre += question.score;
          } else if (question.type === '多选') {
            let flag = true;
            // 多选题需要确保所有选项都被选中
            for (let i = 0; i < this.ans[question.id].length; i++) {
              if (!question.ans.includes(this.ans[question.id][i])) {
                flag = false;
              }
            }
            if (flag && this.ans[question.id].length === question.ans.length) {
              score += question.score;
            }
            allSocre += question.score;
          }
        });
        //alert(`你的得分是：${score}/${allSocre}`);
        addScore(this.trainingPlanId, score + "/" + allSocre).then((res) => {
          if (res.data.code === 1) {
            this.$message.success("交卷成功");
            this.testVisible = false;
            this.getTestQuestionsListForTest();
          }
        }).catch((e) => {
        })

      }).catch(() => {

      });
    },
    //点击移动
    scrollToCard(cardId) {
      // 使用ref属性来获取Vue组件实例
      const cardRef = `card-${cardId}`;
      const cardElement = this.$refs[cardRef] && this.$refs[cardRef][0]?.$el; // 获取卡片元素的 DOM 节点

      //console.log("cardElement", cardElement);

      if (cardElement) {
        // 使用scrollIntoView方法滚动到卡片位置
        cardElement.scrollIntoView({
          behavior: 'smooth', // 平滑滚动
          block: 'start', // 滚动到卡片顶部
          inline: 'nearest' // 滚动到卡片最近的边缘
        });
      }
    }


  },
  mounted() {
    this.getDocumentVideos();
    this.getMyInfo();
  }
};
</script>

<style>
.el-aside {
  padding: 20px;
  height: 100%;
}

.el-tree {
  font-size: 15px;
  /* 调整树字体大小 */
  line-height: 1.5;
  /* 调整行高 */
}

.el-tree-node__content {
  padding: 5px;
  /* 调整节点内边距 */
}

.el-tree-node__label {
  font-weight: bold;
  /* 加粗字体 */
}

.span-ellipsis {
  white-space: nowrap;
  /* 防止文本换行 */
  overflow: hidden;
  /* 隐藏溢出部分 */
  text-overflow: ellipsis;
  /* 使用省略号表示溢出文本 */
}

/* 为选中的节点添加高亮效果 */
.el-tree-node.is-current {

  /* 高亮背景颜色 */
  color: #409eff;
  /* 高亮文本颜色 */
}


* {
  margin: 0;
  padding: 0;
}

.el-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666;
}

.span-ellipsis {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  color: #0a0000;
}

.radio-group .el-radio {
  display: block;
  /* 使每个选项独占一行 */
  margin: 10px 0;
  /* 添加一些垂直间距 */
}

.radio-group {
  text-align: left;
  /* 左对齐单选按钮组 */
}


.checkbox-group {
  text-align: left;
  /* 左对齐复选框组 */
}

.checkbox-group .el-checkbox {
  display: block;
  /* 使每个选项独占一行 */
  margin: 10px 0;
  /* 添加一些垂直间距 */
}

.el-radio__original {
  display: none;
  /* 或者 visibility: hidden; */
}
</style>
